#-*-coding:utf-8-*-
import decimal
import hashlib
import base64
import time
from django.core import serializers
import json
import re
import os
import shutil
import random
import string
import redis
from django.forms import model_to_dict
from django.http import FileResponse
from OnlineJudge.config import config
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.http import JsonResponse,HttpResponse
from OnlineJudge import models
import datetime
from django.contrib.auth.hashers import make_password #引用djago自带的加密解密
from django.core.paginator import Paginator, InvalidPage  # 导入分页器
from django.core.paginator import Paginator,EmptyPage, PageNotAnInteger #导入错误类型
from django.db.models import Aggregate, CharField  # ORM中自定义Concat类实现COUCAT_GROUP的效果




#全局配置redis
redis = redis.Redis(password=config.REDISP_PASS)

from OnlineJudge.models import *
from django.db import connection
import jwt
import datetime
from jwt import exceptions
from django.core.cache import cache
JWT_SALT = 'iv%x6xo7l7_u9bf_u!9#g#m*)*=ej@bek5)(@u3kh*72+unjv='




#生成token
def create_token(payload, timeout=3):

    headers = {
        'typ': 'jwt',
        'alg': 'HS256'
    }
    payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout)
    result = jwt.encode(payload=payload, key=JWT_SALT, algorithm="HS256", headers=headers).decode('utf-8')
    return result


#对token进行和发行校验并获取payload
def parse_payload(token):

    result = {'status': False, 'data': None, 'error': None}
    try:
        verified_payload = jwt.decode(token, JWT_SALT, algorithm="HS256")
        result['status'] = True
        result['data'] = verified_payload
    except exceptions.ExpiredSignatureError:
        result['error'] = 'token已失效'
    except jwt.DecodeError:
        result['error'] = 'token认证失败'
    except jwt.InvalidTokenError:
        result['error'] = '非法的token'
    return result

#判断前端加密后的密码时候和数据库密码一致
#判断密码
def checkPassword(input,password):
    svg = base64.b64decode(bytes(password,'utf-8'))
    svg = svg.decode('utf-8','ignore')
    salt = str(svg)[-4:] #拿盐
    #print(svg)
    #svg等于数据库中密码解密后
    pas = input + salt
    pas = pas.encode('utf-8')
    code = hashlib.sha1(pas).digest()
    code = code.decode('utf-8', 'ignore')
    #code为sha1加密后的密码
    if code+salt == svg:
        return True
    else:
        return False

#md5判断密码是否正确,参数为输入的加密后的密码和数据库密码
def md5CheckPassword(input,password):
    md5 = hashlib.md5(b'jhcoj_mxs') #盐
    md5.update(input.encode(encoding='utf-8'))
    input = md5.hexdigest()
    if input == password:
        return True
    else:
        return False

#给注册用户密码加密
def reg_pass(password):
    md5 = hashlib.md5(b'jhcoj_mxs') #盐
    md5.update(password.encode(encoding='utf-8'))
    md5.hexdigest()
    return md5.hexdigest()

#获取用户ip
def get_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]#所以这里是真实的ip
    else:
        ip = request.META.get('REMOTE_ADDR')#这里获得代理ip
    return ip


#后台生成验证码
def capture(request):
    code_str = string.ascii_letters + string.digits  ##罗列所有字母数字
    def gen_code(len):
        return ''.join(random.sample(code_str, len))  ##随机获取字符，用join的方式将其连接
    code = gen_code(len=4)  ##取5个长度为4的随机序
    #将验证码存储在redis中
    ip = get_ip(request)
    res = redis.setex(ip,60,code)
    code = {"capture":code}
    return code
def capture_two(request):
    code = capture(request)
    return JsonResponse(code)

#验证验证码是否正确
def check_capture(request,code):
    ip = get_ip(request)
    get_code = redis.get(ip)
    if not get_code:
        return False
    if str(code).upper() == str(get_code.decode("utf-8","ignore")).upper():
        return True
    else:
        return False


#判断前端登录数据
def checkLogin(username,password):
    state = True
    if len(password) > 12 or len(password) < 6:
        state = False
    if len(username) > 16 or len(username) < 4:
        state = False
    return state


#判断前端注册数据
def checkRegester(username,password,checkPass,nickname,email,school):
    state = True
    if password != checkPass:
        state = False
    if len(nickname) > 6 or len(nickname) < 3:
        state = False
    if len(password) > 12 or len(password) < 6:
        state = False
    if len(email) > 20 or len(email) < 10:
        state = False
    if len(school) > 15 or len(school) < 3:
        state = False
    if len(username) > 16 or len(username) <4:
        state = False
    if not re.match(r'^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$',email):
        state = False
    return state


#生成邮箱验证码
def email_code(email):
    code_str = string.ascii_letters + string.digits  ##罗列所有字母数字
    def gen_code(len):
        return ''.join(random.sample(code_str, len))  ##随机获取字符，用join的方式将其连接
    code = gen_code(len=6)  ##取6个长度为4的随机序
    #将验证码存储在redis中
    redis.setex(email,43200,code)
    return code


#验证邮箱验证码是否正确
def check_email_code(email,code):
    get_code = redis.get(email)
    if not get_code:
        return False
    if str(code).upper() == str(get_code.decode("utf-8","ignore")).upper():
        return True
    else:
        return False

#将数据库查询的Object数据转为json类型数据方法
def changeToJson(data):
    json_list = []
    for i in data:
        json_dict = model_to_dict(i)
        json_list.append(json_dict)
    return json_list

    #data = serializers.serialize('json', data)
    #data = json.loads(data)
    #return data


#发送邮件
def send_email(email,operation):
    code =email_code(email)
    subject = '52AC平台'
    text_content = '''感谢使用，\
                    如果你看到这条消息，说明你的邮箱服务器不提供HTML链接功能，请联系管理员！'''
    with open("OnlineJudge/utils/email.txt", 'r', encoding='UTF-8') as f:
        html_content = f.read()
    html_content = str(html_content).replace('%operation%',operation)
    html_content = str(html_content).replace('%capture%', code)
    msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, [email])
    msg.attach_alternative(html_content, "text/html")
    status = msg.send()
    if status:
        return True
    else:
        return False

#将获取到的元组数据转为字典类型数据
def tupleToDict(getData):
    data = list(getData)
    returnData = {}
    for i,value in enumerate(data):
        returnData[i] = value
    return returnData



#判断做题结果
def getSolutionResult(problem_id,user_id):
    solution_ture = Solution.objects.filter(user_id=user_id, problem_id=problem_id, result=4)
    solution_falsh = Solution.objects.filter(user_id=user_id, problem_id=problem_id)
    if solution_ture:
        return 'ture'
    elif solution_falsh:
        return 'falsh'
    else:
        return 'none'

#竞赛判断做题结果
def getContestSolutionResult(problem_id,user_id,contest_id):
    solution_true = Solution.objects.filter(user_id=user_id, problem_id=problem_id, contest_id= contest_id,result=4)
    solution_false = Solution.objects.filter(user_id=user_id, problem_id=problem_id,contest_id= contest_id)
    if solution_true:
        return 'true'
    elif solution_false:
        return 'false'
    else:
        return 'none'



#分页查询结果，传参为集合，第几页
def rs_paging(querySet,page):
    paginator = Paginator(querySet, 50)
    try:
        data = paginator.page(page)
    except PageNotAnInteger:
        # 如果请求的页数不是整数, 返回第一页。
        data = paginator.page(1)
    except InvalidPage:
        data = {'err':'找不到页面'}
    except EmptyPage:
        # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
        data = paginator.page(paginator.num_pages)
    return data

#搜索状态页面，传参为问题id，用户id，语言，结果，页数
def searchStatus(problem_id,user_id,language,result,page):
    if language == -1 and result != -1:
        if problem_id != '':
            anwser = Solution.objects.filter(problem_id__contains=problem_id,user_id__contains=user_id,result=result).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(problem_id__contains=problem_id, user_id__contains=user_id, result=result).count()
        else:
            anwser = Solution.objects.filter(user_id__contains=user_id,result=result).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(user_id__contains=user_id, result=result).count()
    elif language != -1 and result == -1:
        if problem_id != '':
            anwser = Solution.objects.filter(problem_id__contains=problem_id,user_id__contains=user_id, language=language).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(problem_id__contains=problem_id, user_id__contains=user_id, language=language).count()
        else:
            anwser = Solution.objects.filter(user_id__contains=user_id,language=language).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(user_id__contains=user_id, language=language).count()
    elif language != -1 and result != -1:
        if problem_id != '':
            anwser = Solution.objects.filter(num__contains=problem_id, user_id__contains=user_id, language=language,result=result).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(problem_id__contains=problem_id, user_id__contains=user_id, language=language,
                                             result=result).count()
        else:
            anwser = Solution.objects.filter(user_id__contains=user_id,language=language,result=result).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(user_id__contains=user_id, language=language, result=result).count()
    else :
        if problem_id != '':
            anwser = Solution.objects.filter(problem_id__contains=problem_id, user_id__contains=user_id).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(problem_id__contains=problem_id, user_id__contains=user_id).count()
        else:
            anwser = Solution.objects.filter(user_id__contains=user_id).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(user_id__contains=user_id).count()
    return anwser,count

# 判断竞赛状态是否为开放
def judgeContest(contest_id):
    time = datetime.datetime.now()
    starttime = Contest.objects.filter(contest_id=contest_id).values('start_time').first()
    starttime = starttime['start_time']
    endtime = Contest.objects.filter(contest_id=contest_id).values('end_time').first()
    endtime = endtime['end_time']
    if time <= endtime and time >= starttime:
        return True
    else:
        return False

#返回权限列表
def getRightStrList(page1,page2):
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM privilege WHERE rightstr IN ('administrator','admin','source_browser','contest_creator','http_judge','problem_editor','password_setter','printer','balloon') ORDER BY user_id, rightstr LIMIT %s, %s",[page1,page2])
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

#竞赛搜索状态页面，传参为问题id，用户id，语言，结果，页数 ,问题
def contestSearchStatus(num,user_id,language,result,page,contest_id):
    if language == -1 and result != -1:
        if num != '':
            anwser = Solution.objects.filter(num__contains=num,user_id__contains=user_id,result=result,contest_id = contest_id).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(num__contains=num, user_id__contains=user_id, result=result,
                                             contest_id=contest_id).count()
        else:
            anwser = Solution.objects.filter(user_id__contains=user_id,result=result,contest_id = contest_id).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(user_id__contains=user_id, result=result, contest_id=contest_id).count()
    elif language != -1 and result == -1:
        if num != '':
            anwser = Solution.objects.filter(num__contains=num,user_id__contains=user_id, language=language,contest_id = contest_id).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(num__contains=num, user_id__contains=user_id, language=language,
                                             contest_id=contest_id).count()
        else:
            anwser = Solution.objects.filter(user_id__contains=user_id,language=language,contest_id = contest_id).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(user_id__contains=user_id, language=language,
                                             contest_id=contest_id).count()
    elif language != -1 and result != -1:
        if num != '':
            anwser = Solution.objects.filter(num__contains=num, user_id__contains=user_id, language=language,result=result,contest_id = contest_id).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(num__contains=num, user_id__contains=user_id, language=language,
                                             result=result, contest_id=contest_id).count()
        else:
            anwser = Solution.objects.filter(user_id__contains=user_id,language=language,result=result,contest_id = contest_id).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(user_id__contains=user_id, language=language, result=result,
                                             contest_id=contest_id).count()
    else :
        if num != '':
            anwser = Solution.objects.filter(num__contains=num, user_id__contains=user_id,contest_id = contest_id).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(num__contains=num, user_id__contains=user_id,
                                             contest_id=contest_id).count()
        else:
            anwser = Solution.objects.filter(user_id__contains=user_id,contest_id = contest_id).order_by('-solution_id')[(page-1)*50:page*50]
            count = Solution.objects.filter(user_id__contains=user_id, contest_id=contest_id).count()
    return anwser,count

# #返回竞赛中所有用户名
# def getUsers(contest_id):
#     with connection.cursor() as cursor:
#         cursor.execute("SELECT user_id FROM (SELECT * FROM solution group by user_id,num) as a WHERE contest_id = %s AND result = 4 GROUP BY user_id ORDER BY COUNT(user_id) DESC",[contest_id])
#         solution_data = cursor.fetchall()
#     returnData = list(solution_data)
#     return returnData

#查询用户做题排名情况，传参为时间datetime，起始，结束
def getRankListByTime(time,begin,end):
    with connection.cursor() as cursor:
        cursor.execute('SELECT u.user_id, nick, s.solved, t.submit FROM users AS u INNER JOIN (SELECT COUNT(DISTINCT problem_id) solved, user_id FROM solution WHERE in_date > %s AND result = 4 GROUP BY user_id ORDER BY solved DESC LIMIT %s, %s) s ON u.user_id = s.user_id INNER JOIN (SELECT COUNT(problem_id) submit, user_id FROM solution WHERE in_date > %s GROUP BY user_id ORDER BY submit DESC) t ON u.user_id = t.user_id ORDER BY s.solved DESC , t.submit, reg_time LIMIT 0, 50',[time,begin,end,time])
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData


#返回竞赛中所有用户编号
def getUsers(contest_id):
    with connection.cursor() as cursor:
        cursor.execute("SELECT user_id FROM solution WHERE contest_id = %s GROUP BY user_id",[contest_id])
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

#返回竞赛中所有问题编号
def getNum(contest_id):
    with connection.cursor() as cursor:
        cursor.execute("SELECT num FROM contest_problem WHERE contest_id = %s GROUP BY num",[contest_id])
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

#返回竞赛中所有问题编号
def getLoginIp(user_id):
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM loginlog WHERE user_id = %s ORDER BY time DESC LIMIT 0,10",[user_id])
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

#返回权限列表中的数据
def getPrivilege(page,content):
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM privilege WHERE user_id LIKE '%%%s%%' OR user_id LIKE '%%%s%%' LIMIT %s,%s" % (content,content,(page-1)*50,page*50))
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

#返回搜索题解列表中的数据
def getProblemSolutionContent(page,content):
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM topic WHERE topic_id LIKE '%%%s%%' OR pid LIKE '%%%s%%' LIMIT %s,%s" % (content,content,(page-1)*50,page*50))
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

#返回题解列表中的数据
def getProblemSolution(page):
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM topic LIMIT %s,%s" % (content,content,(page-1)*50,page*50))
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

#竞赛中第一次提交正确的时间
def getContestFirstRightSubmitTime(contest_id, user_id, num):
    time = Solution.objects.filter(contest_id = contest_id, user_id = user_id, num = num, result= 4).order_by('in_date').values('in_date').first()
    return time

#竞赛中第一次提交正确的时间
def getContestFirstRightNumSubmitTime(contest_id, num):
    time = Solution.objects.filter(contest_id = contest_id, num = num, result= 4).order_by('in_date').values('in_date').first()
    return time

#竞赛中问题写错的次数
def getContestSubmitFalseCount(contest_id, user_id, num):
    errcount = Solution.objects.filter(contest_id = contest_id, user_id = user_id, num = num).exclude(result = 4).count()
    return errcount

#把相隔时间转化为时分秒
def timedeltaChange(time):
    hours, remainder = divmod(time.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    seconds += time.microseconds / 1e6
    hours = time.days * 24 + hours
    time = "{}:{}:{}".format(hours,timeChange(minutes),timeChange(int(seconds)))
    return time

#验证管理员身份
def verifyPrivilege(user_id):
    identities=[]
    listTemp=[]
    listTemp.append(-1)
    identities.append(listTemp)
    temp=Privilege.objects.filter(user_id=user_id,rightstr='administrator',defunct='N').count()
    if temp!=0:
        identities[0][0]=0  #所有功能
        return identities
    else:
        temp = Privilege.objects.filter(user_id=user_id, rightstr='admin',defunct='N').count()
        if temp!=0:
            identities[0][0]=1  #没有以下功能  关卡大类 添加关卡 关卡列表 更改题目ID 导入问题 导出问题 转移源码
            return identities
        else:
            temp = Privilege.objects.filter(user_id=user_id,defunct='N').values('rightstr')
            for data in temp:
                if  data['rightstr']=="problem_editor":   #添加问题 问题列表
                    identities[0].append(2)
                elif data['rightstr']=="source_browser":  #查看代码详情  takeoutCode接口
                    identities[0].append(3)
                elif data['rightstr']=="contest_creator" :   #添加竞赛和作业 竞赛作业列表  问题列表 问题列表
                    identities[0].append(4)
                elif data['rightstr']=="problem_solution" :  #题解列表
                    identities[0].append(5)
                elif data['rightstr']=="http_judge":      #在线判题（空）
                    identities[0].append(6)
                elif data['rightstr']=="password_setter" :     #修改密码
                    identities[0].append(7)
                elif data['rightstr']=="balloon & printer" :   #气球（空）
                    identities[0].append(8)
                elif data['rightstr']=="class_manager":     #班级管理
                    identities[0].append(9)
                else :
                    identities.append(data['rightstr'])   #c后面为竞赛id   报名竞赛or管理员添加竞赛时为用户报名得到权限，
            return identities


# ORM中自定义Concat类实现COUCAT_GROUP的效果
class Concat(Aggregate):
    function = 'GROUP_CONCAT'
    template = '%(function)s(%(distinct)s%(expressions)s)'
    def __init__(self,expression,distinct=False,**extra):
        super(Concat,self).__init__(
            expression,
            distinct='DISTINCT' if distinct else '',
            output_field=CharField(),
            **extra)


#确认用户是否点赞，参数为用户名和题解id
def isPraised(user_id,topic_id):
    with connection.cursor() as cursor:
        cursor.execute("SELECT COUNT(user_id) FROM praise WHERE user_id = %s and topic_id = %s",[user_id,topic_id])
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

def getEveryResult(user_id):
    with connection.cursor() as cursor:
        cursor.execute("SELECT problem_id,count(problem_id) FROM solution WHERE result = 4 AND user_id = %s GROUP BY problem_id",[user_id])
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

#返回日期之间的提交总数
def getTimeSubmit(starttime,endtime,user_id):
    with connection.cursor() as cursor:
        cursor.execute("SELECT COUNT(user_id) FROM solution WHERE in_date BETWEEN %s AND %s and user_id = %s",[starttime,endtime,user_id])
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

#返回日期之间的正确总数
def getTimeSolved(starttime,endtime,user_id):
    with connection.cursor() as cursor:
        cursor.execute("SELECT COUNT(user_id) FROM solution WHERE in_date BETWEEN %s AND %s and user_id = %s and result = 4",[starttime,endtime,user_id])
        solution_data = cursor.fetchall()
    returnData = list(solution_data)
    return returnData

#整数改为时间
def timeChange(time):
    time = str(time)
    if len(time) == 2:
        time = time
    elif len(time) == 1:
        time = '0'+ time
    return time


#管理员提交问题  ——处理测试用例 创建文件
def test_create(problem_id,name, msg):
    #../../../data/%s
    data_path = "..//..//judge//data//%s//"%problem_id  # 新创建的txt文件的存放路径
    isExists = os.path.exists(data_path)
    judge=0
    if not isExists:
        os.makedirs(data_path)
        judge=1
    full_path = data_path + name  # 也可以创建一个.doc的word文档
    file = open(full_path, 'w')
    file.truncate()
    file.write(msg)
    file.close()
#管理员提交问题  ——处理测试用例 读取文件
def test_read(problem_id,name):
    data_path = "..//..//judge//data//%s//" % problem_id  # 新创建的txt文件的存放路径
    isExists = os.path.exists(data_path)
    if not isExists:
        return ''
    full_path = data_path + name   # 也可以创建一个.doc的word文档
    try:
        file = open(full_path, 'r')
        msg=file.read()
        file.close()
    except IOError:
        return None
    return msg
#管理员问题列表  ——处理测试用例 删除题目文件夹及test文件
def list_delete(problem_id):
    data_path = "..//..//judge//data//%s//" % problem_id  # 新创建的txt文件的存放路径
    filelist=[]
    filelist=os.listdir(data_path)
    for f in filelist:
        filepath = os.path.join( data_path, f )
        os.remove(filepath)
    os.rmdir(data_path)


#管理员问题列表  ——读取若干 测试用例
def list_read(problem_id):
    data_path = "..//..//judge//data//%s//" % problem_id     #新创建的txt文件的存放路径  默认地址为/home/jhcoj/Online_judge

    fifeInfos=[]
    filelist=os.listdir(data_path)
    for f in filelist:
        if f=='sample.input' or f=='sample.out':
            continue
        fifeInfo={}
        fpath = os.path.join( data_path, f )
        fifeInfo['size']=os.path.getsize(fpath)
        fifeInfo['createTime'] =os.path.getctime(fpath)
        file=os.path.splitext(f)
        fifeInfo['name'] = f
        fifeInfo['type']=file[1]
        fifeInfos.append(fifeInfo)
    return fifeInfos

# 管理员问题列表  ——测试用例 重命名
def file_rename(problem_id,name,rename):
    data_path = "..//..//judge//data//%s//" % problem_id  # 新创建的txt文件的存放路径
    full_path = data_path + name  # 也可以创建一个.doc的word文档
    edit_path = data_path + rename  # 也可以创建一个.doc的word文档
    os.rename(full_path,edit_path)
    return True
# 管理员问题列表  ——测试用例 删除
def file_delete(problem_id,name):
    data_path = "..//..//judge//data//%s//" % problem_id  # 新创建的txt文件的存放路径
    full_path = data_path + name   # 也可以创建一个.doc的word文档
    os.remove(full_path)
    return True

#1和15的转化
def oneAndFifteen(day):
    if day == 15:
        day = 1
    elif day == 1:
        day = 15
    return day

# 判断用户限制IP状态
def judgeLoginIp(user_id,time):
    judge=UserIp.objects.filter(user_id=user_id).order_by('-start_time')[:1]
    for data in judge:
        time = time.strftime('%Y-%m-%d %H:%M:%S')
        time2=data.start_time.strftime('%Y-%m-%d %H:%M:%S')
        d1 = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
        d2 = datetime.datetime.strptime(time2, '%Y-%m-%d %H:%M:%S')
        second = (d1 - d2).seconds
        limitSecond=int(data.during)*3600
        if second>limitSecond:
            #  UserIp.objects.filter(user_id=user_id).delete()   #删除过期记录
            return False   #限制解除
        else:
            return limitSecond-second  #被限制，则返回剩余秒数


def test_down(problem_id, name):
    data_path = "..//..//judge//data//%s//" % problem_id  # 新创建的txt文件的存放路径
    full_path = data_path + name  # 也可以创建一个.doc的word文档
    try:
        response = FileResponse(open(full_path, 'rb'))
        response['content_type'] = "application/octet-stream"
        response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(full_path)
        return response
    except Exception:
        return False

def getLog(contest_id):
    f1 = open("..//..//judge//data//contestLogs", 'w', encoding='utf-8')
    solution_data = ''
    solution = Solution.objects.filter(contest_id=contest_id).all()
    for data in solution:
        p_status = ["等待....", "等待重判", "编译中...", "运行并评判", "正确", "格式错误", "答案错误", "时间超限", "内存超限", "输出超限", "运行错误", "编译错误",
                    "运行完成"]
        result = p_status[data.result]
        code = SourceCode.objects.filter(solution_id=data.solution_id).first()
        solution_data = str(solution_data) + data.user_id + 'problem' + str(data.problem_id) + str(result) + '\n' + code.source +'\n' + '\n------------------------------------------------------\n'
    f1.write(solution_data)
    f1.close()
    response = FileResponse(open('..//..//judge//data//contestLogs', 'rb'))
    response['content_type'] = "application/octet-stream"
    response['Content-Disposition'] = 'attachment; filename=contestLogs'
    return response


# def judgingContest(contest_id):
#     contest = Contest.objects.filter(contest_id=contest_id).first()
#     now = datetime.datetime.now()
#     if now > contest.start_time and now < contest.end_time:
#         return True
#     else:
#         return False

#重判题目    使用
def reJudge(rj):
    dct = {}
    problems = Solution.objects.filter(problem_id=rj)
    for problem in problems:
        dct['problem_id'] = int(problem.problem_id)
        dct['user_id'] = problem.user_id
        dct['language'] = int(problem.language)
        dct['ip'] = problem.ip
        dct['contest_id'] = int(problem.contest_id)
        dct['num'] = int(problem.num)
        dct['code_length'] = int(problem.code_length)
        dct['valid'] = int(problem.valid)
        dct['time'] = int(problem.time)
        dct['memory'] = int(problem.memory)
        dct['in_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        dct['result'] = int(problem.result)
        dct['judgetime'] = problem.judgetime
        dct['pass_rate'] = decimal.Decimal(problem.pass_rate)
        dct['lint_error'] = int(problem.lint_error)
        dct['judger'] = problem.judger
        dct['result'] = 1
        Solution.objects.create(**dct)

#判断今天是否是本月的第一天
def firstDayOfMonth(dt):
   return (dt + datetime.timedelta(days= -dt.day + 1)).replace(hour=0, minute=0, second=0, microsecond=0)

#判断权限
def JudgmentAuthority(user_id,power):
    rightstr_data = []
    rightstrs = Privilege.objects.filter(user_id=user_id).values('rightstr')
    for data in rightstrs:
        rightstr_data.append(data['rightstr'])
    try:
        int(power)
        new_power = 'c' + power
        if new_power in rightstr_data:
            return True
        else:
            return False
    except:
        if power in rightstr_data:
            return True
        else:
            return False


#获取当前排名
def getUserContestRank(user_id,contest_id):
    total = 0
    starttime = Contest.objects.filter(contest_id=contest_id).values('start_time').first()
    starttime = starttime['start_time']
    users = getUsers(contest_id)
    nums = getNum(contest_id)
    contestRank = []
    for user in users:
        user = ''.join(map(str, user))
        now = datetime.datetime.now()
        sumtime = now - now
        sumsolved = 0
        contestNum = []
        contesttime = []
        sumerrcount = 0
        for num in nums:
            num = ''.join(map(str, num))
            time = getContestFirstRightSubmitTime(contest_id, user, num)
            errcount_data = getContestSubmitFalseCount(contest_id, user, num)
            sumerrcount = int(errcount_data) + sumerrcount
            if time:
                time = time['in_date']
                time = time-starttime
                sumsolved = sumsolved + 1
                rstime = timedeltaChange(time)
            else:
                timenow = datetime.datetime.now()
                time = timenow - timenow
                rstime = timedeltaChange(time)

            num = chr(int(num)+65)
            contestNum.append(num)
            contesttime.append(rstime)
            sumtime = sumtime + time
        sumtime = timedeltaChange(sumtime)
        contestRank.append(
            {
                'user': user,
                'contestNum': contestNum,
                'contesttime':contesttime,
                'sumtime': sumtime,
                'sumsolved': sumsolved,
                'sumerrcount':sumerrcount,
            }
        )
    contestRank = sorted(contestRank,key=lambda x:(-x["sumsolved"],x['sumtime'],-x['sumerrcount']))
    for data in contestRank:
        if data['user'] == user_id:
            total += 1
            break
    return total


#全局变量
def variable():

        problem_count = Problem.objects.count()  # 题目总数
        submit_count = Solution.objects.count()  # 提交的总数
        Users_count = Users.objects.count()  # 用户总数
        # 近期六条竞赛
        contests = Contest.objects.filter(private__lt=2, defunct='N').order_by('-start_time')[:6]
        day_rank = getRankListByTime(datetime.datetime.now() - datetime.timedelta(days=1), 0, 10)  # 每日排名
        week_rank = getRankListByTime(datetime.datetime.now() - datetime.timedelta(days=7), 0, 10)  # 每周排名
        month_rank = getRankListByTime(datetime.datetime.now() - datetime.timedelta(days=30), 0, 10)  # 每月排名
        day_subimt_count = Solution.objects.filter(in_date__gte=datetime.datetime.now() - datetime.timedelta(days=1)).count()
        cache.__setattr__("problem_count", problem_count)
        cache.__setattr__("submit_count", submit_count)
        cache.__setattr__("users_count", Users_count)
        if contests:
            cache.__setattr__("contests", contests)
        else:
            cache.__setattr__("contests", ' ')
        cache.__setattr__("day_rank", day_rank)
        cache.__setattr__("week_rank", week_rank)
        cache.__setattr__("month_rank", month_rank)
        cache.__setattr__("day_subimt_count", day_subimt_count)

#更新新闻
def NewsChange():

    newsList = News.objects.only('news_id', 'title', 'time').filter(defunct='N').order_by('-importance', '-time')[0:10]
    cache.__setattr__("newsList", newsList)


NewsChange()
variable()


